<?php
/*
Plugin Name: Awstats
Plugin URI: http://www.curioso.org/awstats/
Description: Retrieves info from Awstats.
Version: 1.0a
Author: Curioso
Author URI: http://www.curioso.org/
*/

// Change these two lines if the default values do not work
//
$awstats_dir = '/var/lib/awstats';
$awstats_site = awstats_getsite(get_settings('siteurl'));

function awstats_getsite ($url) {
	preg_match("/^(http:\/\/)?([^\/]+)/i", $url, $m);
	return $m[2];
}

function awstats_read_history () {
	global $awstats_text, $awstats_dir, $awstats_site, $awstats_period;
	global $wpdb, $month;

	if (isset($_GET['m'])) {
		$m = ''.intval($_GET['m']);
	}
	if (isset($_GET['monthnum'])) {
		$monthnum = ''.intval($_GET['monthnum']);
	}
	if (isset($_GET['year'])) {
		$year = ''.intval($_GET['year']);
	}
	if (isset($_GET['w'])) {
		$w = ''.intval($_GET['w']);
	}

	if (!empty($monthnum) && !empty($year)) {
		$mm = ''.zeroise(intval($monthnum), 2);
		$yyyy = ''.intval($year);
	} elseif (!empty($w)) {
		$yyyy = ''.intval(substr($m, 0, 4));
		$d = (($w - 1) * 7) + 6;
		$mm = $wpdb->get_var(
			"SELECT DATE_FORMAT((DATE_ADD('${yyyy}0101', 
					              INTERVAL $d DAY)), 
				   	    '%m')");
	} elseif (!empty($m)) {
		$yyyy = ''.intval(substr($m, 0, 4));
		if (strlen($m) < 6) {
		    $mm = '01';
		} else {
		    $mm = ''.zeroise(intval(substr($m, 4, 2)), 2);
		}
	} else {
		$yyyy = gmdate('Y', current_time('timestamp'));
		$mm = gmdate('m', current_time('timestamp'));
	}

	$path = "$awstats_dir/awstats$mm$yyyy.$awstats_site.txt";
	if (is_readable($path)) {
		$awstats_text = file($path);
		$awstats_text = implode('', $awstats_text);

		$awstats_period = "$month[$mm] $yyyy";
	}
}

function awstats_read_section($section) {
	global $awstats_text;

	if (preg_match('/\nBEGIN_'.$section.' \d+\n(.*)\nEND_'.$section.'\n/s',
			 $awstats_text, $match)) {
		foreach (explode("\n", $match[1]) as $row) 
			$lines[] = split(' ', $row);
	}
	return $lines;
}

function awstats_table_searchwords ($max = 36) {
	$strings = awstats_read_section('SEARCHWORDS');
	if (!$strings) return;
	$n = count($strings);
	if ($n == 0) return;
	if ($n > $max) $n = $max;

	$t  = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n";
	$t .= "\t<tr><th>Search Strings</th><th class=\"last\">Hits</th></tr>\n";
	for ($i = 0; $i < $n; $i++) {
	    $s = $strings[$i][0];
	    $c = $strings[$i][1];
	    $t .= "\t<tr><td>$s</td><td class=\"last\">$c</td></tr>\n";
	}
	$t .= "</table>";

	return $t;
}

function awstats_searchwords ($max = 10, $title = '') {
	$strings = awstats_read_section('SEARCHWORDS');
	if (!$strings) return;
	$n = count($strings);
	if ($n == 0) return;
	$r = $title ? "<li id=\"searchwords\">$title" : "";
	if ($n > $max) $n = $max;
	$r .= "<ul>\n";
	for ($i = 0; $i < $n; $i++) {
		$s = $strings[$i][0];
		$c = $strings[$i][1];
		$r .= "<li><a href=\"http://www.google.com/search?q=$s\">";
		$r .= strtr($s, '+', ' ');
		$r .= "</a> ($c)</li>\n";
	}
	$r .= $title ? "</ul></li>\n" : "</ul>\n";
	echo $r;
}

function awstats_compare_pages ($a, $b) {
	$r = ($a[1] > $b[1]) ? -1 : (($a[1] < $b[1]) ?  1 : 0);
	return $r;
}

function awstats_popular ($max = 10, $title = '') {
	global $wpdb;

	$list = awstats_read_section('SIDER');
	if (!$list || count($list) == 0) return;
	usort($list, 'awstats_compare_pages');
	$n = 0;
	$r = $title ? "<li id=\"popular\">$title" : "";
	$r .= "<ul>\n";
	foreach ($list as $line) {
		$u = $line[0];
		$c = $line[1];
		if (strpos($u, '/feed/') !== false) {
			// Do not display feeds
		} else if ($u == '/') {
			// Do not display links to main blog
		} else if (preg_match('|/\d\d\d\d/?(\d\d)?/?$|', $u)) {
			// Do not display year/month links
		} else if ($id = url_to_postid($u)) {
			$t = '';
			while ($id) {
				$p = $wpdb->get_row("SELECT post_title, 
							    post_parent 
						     FROM $wpdb->posts
						     WHERE ID = $id");
				if ($t)
					$t = stripslashes($p->post_title) .
					     " &raquo; $t";
				else
					$t = stripslashes($p->post_title);
				$id = $p->post_parent;
			}
			$r .= "<li><a href=\"$u\">$t</a> ($c)</li>\n";
			if ($n++ == $max) break;
		}
	}
	$r .= $title ? "</ul></li>\n" : "</ul>\n";
	echo $r;
}

function awstats_referrers ($max = 10, $title = '') {
	$list = awstats_read_section('PAGEREFS');
	if (!$list || count($list) == 0) return;
	usort($list, 'awstats_compare_pages');
	$n = 0;
	$r = $title ? "<li id=\"referrers\">$title" : "";
	$r .= "<ul>\n";
	foreach ($list as $line) {
		$u = $line[0];
		$c = $line[1];
		if (check_comment('', '', $u, '', '')) {
			$s = awstats_getsite($u);
			$r .= "<li><a href=\"$u\" rel=\"nofollow\">$s</a> ($c)</li>\n";
			if ($n++ == $max) break;
		}
	}
	$r .= "</ul>\n";
	echo $r;
}

function awstats_browsers ($title = '') {
	$abb = array (
		'msie' => 'Internet Explorer',
		'firefox' => 'Firefox',
		'netscape' => 'Netscape',
		'mozilla' => 'Mozilla',
		'camino' => 'Camino',
		'safari' => 'Safari',
		'netnewswire' => 'NetNewsWire',
		'opera' => 'Opera',
		'lynx' => 'Lynx',
		'' => 'Other'
	);
	$browsers = awstats_read_section('BROWSER');
	if (!$browsers || count($browsers) == 0) return;
	$stats = array();
	$total = 0;
	foreach ($browsers as $browser) {
		foreach ($abb as $key => $val) {
			if (!$key ||
			    strpos($browser[0], $key) === 0) {
				$stats[$val] += $browser[1];
				$total += $browser[1];
				break;
			}
		}
	}
	arsort($stats, SORT_NUMERIC);
	$r = $title ? "<li id=\"browsers\">$title" : "";
	$r .= "<ul>\n";
	foreach ($stats as $key => $val) {
		$percent = round(100 * $val / $total);
		$r .= "<li>$key ($percent%)</li>\n";
	}
	$r .= $title ? "</ul></li>\n" : "</ul>\n";
	echo $r;
}

if (!isset($wpdb->posts)) {
        $wpdb->posts               = $table_prefix . 'posts';
        $wpdb->users               = $table_prefix . 'users';
        $wpdb->categories          = $table_prefix . 'categories';
        $wpdb->post2cat            = $table_prefix . 'post2cat';
        $wpdb->comments            = $table_prefix . 'comments';
        $wpdb->links               = $table_prefix . 'links';
        $wpdb->linkcategories      = $table_prefix . 'linkcategories';
        $wpdb->options             = $table_prefix . 'options';
        $wpdb->optiontypes         = $table_prefix . 'optiontypes';
        $wpdb->optionvalues        = $table_prefix . 'optionvalues';
        $wpdb->postmeta            = $table_prefix . 'postmeta';
}

awstats_read_history();
add_action('awstats_browsers', 'awstats_browsers', 10, 1);
add_action('awstats_popular', 'awstats_popular', 10, 2);
add_action('awstats_referrers', 'awstats_referrers', 10, 2);
add_action('awstats_searchwords', 'awstats_searchwords', 10, 2);
?>
